<template>
  <div style="background-color: #f0f2f5; padding: 0px;">
    <PageHeader
      :breadcrumb="breadcrumb"
      style="background-color: white; padding: 24px; margin-bottom: 16px;"
    />
    <div style="background-color: white; padding: 24px; padding-top: 0px;">
      <div id="operationButton">
        <a-button
          v-if="canAddAssay"
          size="large"
          type="primary"
          @click="onAddButtonClick"
        >
          添加
        </a-button>
        &nbsp;
        <a-button
            size="large"
            type="primary"
            @click="onRefresh"
        >
          刷新
        </a-button>
        <a-modal
          v-model:visible="addOrEditDialogVisible"
          :title="addOrEditDialogTitle"
          :width="600"
          :keyboard="false"
          :maskClosable="false"
          :footer="null"
          :destroyOnClose="true"
          centered
        >
          <AddOrEditAssay
            :url="editUrl"
            @operate-success="onAddOrEditSuccess"
            @operate-failed="closeAddOrEditDialog"
          />
        </a-modal>
      </div>
      <a-table
        :loading="loading"
        :columns="columns"
        :data-source="data"
        :pagination="{ pageSize: 10 }"
        :scroll="{ x: 240 }"
      >
        <template
          v-if="canEditAssay || canDeleteAssay"
          #operation="{ record }"
        >
          <TableOperation
            :canEdit="canEditAssay"
            :canDelete="canDeleteAssay"
            @edit="onEdit(record.key)"
            @delete="onDelete(record.key)"
          />
        </template>
        <template #filterDropdown="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }">
          <div style="padding: 8px">
            <a-input
                :ref="c => (searchInput = c)"
                :placeholder="`查询 ${column.title}`"
                :value="selectedKeys[0]"
                style="width: 188px; margin-bottom: 8px; display: block;"
                @change="e => setSelectedKeys(e.target.value ? [e.target.value] : [])"
                @pressEnter="handleSearch(selectedKeys, confirm, column.dataIndex)"
            />
            <a-button
                type="primary"
                size="small"
                style="width: 90px; margin-right: 8px"
                @click="handleSearch(selectedKeys, confirm, column.dataIndex)"
            >
              <template #icon>
                <SearchOutlined/>
              </template>
              查询
            </a-button>
            <a-button size="small" style="width: 90px" @click="handleReset(clearFilters)">
              重置
            </a-button>
          </div>
        </template>
        <template #filterIcon="filtered">
          <search-outlined :style="{ color: filtered ? '#108ee9' : undefined }"/>
        </template>
        <template #customRender="{ text, column }">
              <span v-if="searchText && searchedColumn === column.dataIndex">
                <template
                    v-for="(fragment, i) in text
                    .toString()
                    .split(new RegExp(`(?<=${searchText})|(?=${searchText})`, 'i'))"
                >
                  <mark
                      v-if="fragment.toLowerCase() === searchText.toLowerCase()"
                      :key="i"
                      class="highlight"
                  >
                    {{ fragment }}
                  </mark>
                  <template v-else>{{ fragment }}</template>
                </template>
              </span>
          <template v-else>
            {{ text }}
          </template>
        </template>
      </a-table>
    </div>
  </div>
</template>
<script>

import AddOrEditAssay from './AddOrEditAssay'
import TableOperation from '../../Common/TableOperation'
import { message } from 'ant-design-vue'
import PageHeader from "@/components/Contents/Common/PageHeader";
import moment from 'moment'
import {SearchOutlined} from '@ant-design/icons-vue'


const operationColumn = {
  title: '操作',
  dataIndex: 'operation',
  slots: { customRender: 'operation' },
  width: 150,
}

export default {
  name: 'Assay',
  emits: ['add'],
  components: {
    PageHeader,
    AddOrEditAssay,
    TableOperation,
    SearchOutlined
  },
  data() {
    const refreshInterval = 100
    return {
      breadcrumb: [
        { key: 1, title: '实验管理' },
        { key: 2, title: '分析检测' },
      ],
      data: [],
      loading: false,
      addOrEditDialogVisible: false,
      addOrEditDialogTitle: '',
      editUrl: '',
      canAddAssay: false,
      canEditAssay: false,
      canDeleteAssay: false,
      columns: [],
      searchText: '',
      searchInput: null,
      searchedColumn: '',
      refreshInterval,
    }
  },
  mounted() {
    this.columns = this.getDataColumns()
    this.processPermission()
    this.fetch()
  },
  methods: {
    getDataColumns() {
      return [
        {
          title: '实验名称',
          dataIndex: 'experiment_name',
          width: 150,
          key: 'experiment_name',
          slots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'customRender',
          },
          onFilter: (value, record) =>
              record.name
                  .toString()
                  .toLowerCase()
                  .includes(value.toLowerCase()),
          onFilterDropdownVisibleChange: visible => {
            if (visible) {
              setTimeout(() => {
                // console.log(this.searchInput);
                this.searchInput.focus();
              }, 0);
            }
          },
        },
        {
          title: '样品编号',
          dataIndex: 'sample_num',
          width: 150,
          key: 'sample_num',
          slots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'customRender',
          },
          onFilter: (value, record) =>
              record.name
                  .toString()
                  .toLowerCase()
                  .includes(value.toLowerCase()),
          onFilterDropdownVisibleChange: visible => {
            if (visible) {
              setTimeout(() => {
                // console.log(this.searchInput);
                this.searchInput.focus();
              }, 0);
            }
          },
        },
        {
          title: '样品名称',
          dataIndex: 'sample_name',
          width: 150,
          key: 'sample_name',
          slots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'customRender',
          },
          onFilter: (value, record) =>
              record.name
                  .toString()
                  .toLowerCase()
                  .includes(value.toLowerCase()),
          onFilterDropdownVisibleChange: visible => {
            if (visible) {
              setTimeout(() => {
                // console.log(this.searchInput);
                this.searchInput.focus();
              }, 0);
            }
          },
        },
        {
          title: '样品状态',
          dataIndex: 'sample_status',
          width: 150,
          key: 'sample_status',
          slots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'customRender',
          },
          onFilter: (value, record) =>
              record.name
                  .toString()
                  .toLowerCase()
                  .includes(value.toLowerCase()),
          onFilterDropdownVisibleChange: visible => {
            if (visible) {
              setTimeout(() => {
                // console.log(this.searchInput);
                this.searchInput.focus();
              }, 0);
            }
          },
        },
        {
          title: '样品数量',
          dataIndex: 'sample_quantity',
          width: 150,
          key: 'sample_quantity',
          slots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'customRender',
          },
          onFilter: (value, record) =>
              record.name
                  .toString()
                  .toLowerCase()
                  .includes(value.toLowerCase()),
          onFilterDropdownVisibleChange: visible => {
            if (visible) {
              setTimeout(() => {
                // console.log(this.searchInput);
                this.searchInput.focus();
              }, 0);
            }
          },
        },
        {
          title: '送样人员',
          dataIndex: 'delivery_personnel',
          width: 150,
          key: 'delivery_personnel',
          slots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'customRender',
          },
          onFilter: (value, record) =>
              record.name
                  .toString()
                  .toLowerCase()
                  .includes(value.toLowerCase()),
          onFilterDropdownVisibleChange: visible => {
            if (visible) {
              setTimeout(() => {
                // console.log(this.searchInput);
                this.searchInput.focus();
              }, 0);
            }
          },
        },
        {
          title: '检测机构',
          dataIndex: 'testing_facility',
          width: 150,
          key: 'testing_facility',
          slots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'customRender',
          },
          onFilter: (value, record) =>
              record.name
                  .toString()
                  .toLowerCase()
                  .includes(value.toLowerCase()),
          onFilterDropdownVisibleChange: visible => {
            if (visible) {
              setTimeout(() => {
                // console.log(this.searchInput);
                this.searchInput.focus();
              }, 0);
            }
          },
        },
        {
          title: '委托书编号',
          dataIndex: 'attorney_number',
          width: 150,
          key: 'attorney_number',
          slots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'customRender',
          },
          onFilter: (value, record) =>
              record.name
                  .toString()
                  .toLowerCase()
                  .includes(value.toLowerCase()),
          onFilterDropdownVisibleChange: visible => {
            if (visible) {
              setTimeout(() => {
                // console.log(this.searchInput);
                this.searchInput.focus();
              }, 0);
            }
          },
        },
        {
          title: '检测编号',
          dataIndex: 'test_num',
          width: 150,
          key: 'test_num',
          slots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'customRender',
          },
          onFilter: (value, record) =>
              record.name
                  .toString()
                  .toLowerCase()
                  .includes(value.toLowerCase()),
          onFilterDropdownVisibleChange: visible => {
            if (visible) {
              setTimeout(() => {
                // console.log(this.searchInput);
                this.searchInput.focus();
              }, 0);
            }
          },
        },
        {
          title: '送样日期',
          dataIndex: 'delivery_date',
          width: 150,
          key: 'delivery_date',
          slots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'customRender',
          },
          onFilter: (value, record) =>
              record.name
                  .toString()
                  .toLowerCase()
                  .includes(value.toLowerCase()),
          onFilterDropdownVisibleChange: visible => {
            if (visible) {
              setTimeout(() => {
                // console.log(this.searchInput);
                this.searchInput.focus();
              }, 0);
            }
          },
        },
        {
          title: '完成日期',
          dataIndex: 'finish_date',
          width: 150,
          key: 'finish_date',
          slots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'customRender',
          },
          onFilter: (value, record) =>
              record.name
                  .toString()
                  .toLowerCase()
                  .includes(value.toLowerCase()),
          onFilterDropdownVisibleChange: visible => {
            if (visible) {
              setTimeout(() => {
                // console.log(this.searchInput);
                this.searchInput.focus();
              }, 0);
            }
          },
        },
        {
          title: '分析检测报告',
          dataIndex: 'riddle_report',
          width: 150,
          key: 'riddle_report',
          slots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'customRender',
          },
          onFilter: (value, record) =>
              record.name
                  .toString()
                  .toLowerCase()
                  .includes(value.toLowerCase()),
          onFilterDropdownVisibleChange: visible => {
            if (visible) {
              setTimeout(() => {
                // console.log(this.searchInput);
                this.searchInput.focus();
              }, 0);
            }
          },
        },
        {
          title: '主检测设备',
          dataIndex: 'main_testing_equipment',
          width: 150,
          key: 'main_testing_equipment',
          slots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'customRender',
          },
          onFilter: (value, record) =>
              record.name
                  .toString()
                  .toLowerCase()
                  .includes(value.toLowerCase()),
          onFilterDropdownVisibleChange: visible => {
            if (visible) {
              setTimeout(() => {
                // console.log(this.searchInput);
                this.searchInput.focus();
              }, 0);
            }
          },
        },
        {
          title: '实验金额',
          dataIndex: 'experiment_amount',
          width: 150,
          key: 'experiment_amount',
          slots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'customRender',
          },
          onFilter: (value, record) =>
              record.name
                  .toString()
                  .toLowerCase()
                  .includes(value.toLowerCase()),
          onFilterDropdownVisibleChange: visible => {
            if (visible) {
              setTimeout(() => {
                // console.log(this.searchInput);
                this.searchInput.focus();
              }, 0);
            }
          },
        },
        {
          title: '附件',
          dataIndex: 'annex',
          width: 150,
          key: 'annex',
          slots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'customRender',
          },
          onFilter: (value, record) =>
              record.name
                  .toString()
                  .toLowerCase()
                  .includes(value.toLowerCase()),
          onFilterDropdownVisibleChange: visible => {
            if (visible) {
              setTimeout(() => {
                // console.log(this.searchInput);
                this.searchInput.focus();
              }, 0);
            }
          },
        },
      ]
    },
    // 处理权限
    processPermission() {
      this.axios
        .get(
          '/has_permission?permission=experiment_management.add_riddle'
        )
        .then((res) => {
          this.canAddAssay = res.data.result
        })
        .catch((error) => {
          console.log('Error', error.message)
        })
      this.axios
        .get(
          '/has_permission?permission=experiment_management.change_riddle'
        )
        .then((res) => {
          this.canEditAssay = res.data.result
          let last = this.columns.length
          if (
            this.columns[last - 1].dataIndex !== 'operation' &&
            this.canEditAssay
          ) {
            this.columns.push(operationColumn)
          }
        })
        .catch((error) => {
          console.log('Error', error.message)
        })
      this.axios
        .get(
          '/has_permission?permission=experiment_management.delete_riddle'
        )
        .then((res) => {
          this.canDeleteAssay = res.data.result
          let last = this.columns.length
          if (
            this.columns[last - 1].dataIndex !== 'operation' &&
            this.canDeleteAssay
          ) {
            this.columns.push(operationColumn)
          }
        })
        .catch((error) => {
          console.log('Error', error.message)
        })
    },
    // 从后端获取数据
    fetch() {
      this.loading = true
      let updatedData = []
      this.axios
        .get('/experiment_management/riddle/')
        .then((res) => {
          const data = res.data
          for (let i = 0; i < data.length; ++i) {
            let delivery_date = null
            let finish_date = null
            if(moment(data[i].delivery_date).isValid())
              delivery_date = data[i].delivery_date.substring(0,10)
            if(moment(data[i].finish_date).isValid())
              finish_date = data[i].finish_date.substring(0,10)
            updatedData.push({
              key: data[i].url,
                  experiment_name: data[i].readable_experiment_name,
                  sample_num: data[i].sample_num,
                  sample_name: data[i].sample_name,
                  sample_status: data[i].sample_status,
                  sample_quantity: data[i].sample_quantity,
                  delivery_personnel: data[i].delivery_personnel,
                  testing_facility: data[i].testing_facility,
                  attorney_number: data[i].attorney_number,
                  test_num: data[i].test_num,

                  delivery_date:  delivery_date,
                      //moment(data[i].delivery_date).format('YYYY-MM-DDTHH:mm:ss'),
                  finish_date: finish_date,
                  riddle_report: data[i].riddle_report_filename,
                  main_testing_equipment: data[i].main_testing_equipment,
                  experiment_amount: data[i].experiment_amount,
                  annex: data[i].annex_filename,


              // sample_name: data[i].sample_name,
              // alloy_code: data[i].readable_alloy_code,
              // corrosion_potential: data[i].corrosion_potential,
              // corrosion_current: data[i].corrosion_current,
              // permeability: data[i].erosion,
              // passivation_current: data[i].passivation_current,
              // polarization_curve: data[i].polarization_curve_filename,
              // open_circuit_potential: data[i].open_circuit_potential,
              // open_circuit_potential_curve:
              //   data[i].open_circuit_potential_curve_filename,
              // corrosion_rate: data[i].corrosion_rate,
              // thermogravimetric_curve: data[i].tg_curve_filename,
              // toxicity: data[i].toxicity,
            })
          }
          setTimeout(() => {
            this.data = updatedData
            this.loading = false
          }, this.refreshInterval)
          // this.loading = false
          // console.log('chemical:', res)
        })
        .catch((error) => {
          setTimeout(() => {
            this.loading = false
          }, this.refreshInterval)
          console.log('Error', error.message)
        })
    },
    onAddButtonClick() {
      this.addOrEditDialogTitle = '添加分析检测信息'
      this.editUrl = ''
      this.addOrEditDialogVisible = true
      // this.$emit('add')
    },
    onAddOrEditSuccess() {
      this.closeAddOrEditDialog()
      this.fetch()
    },
    closeAddOrEditDialog() {
      this.addOrEditDialogVisible = false
      this.fetch()
    },
    onEdit(key) {
      this.addOrEditDialogTitle = '编辑分析检测信息'
      // console.log(key)
      this.editUrl = key
      this.addOrEditDialogVisible = true
    },
    onDelete(key) {
      message.loading({ content: '删除中...', key })
      const data = [...this.data]
      this.axios
        .delete(key)
        .then(() => {
          setTimeout(() => {
            message.success({ content: '删除成功！', key, duration: 2 })
            this.data = data.filter((item) => item.key !== key)
          }, 1000)
        })
        .catch((error) => {
          setTimeout(() => {
            message.error({ content: '删除失败！', key, duration: 2 })
          }, 1000)
          console.log('Error', error.message)
        })
    },
    handleSearch(selectedKeys, confirm, dataIndex) {
      confirm();
      // console.log(selectedKeys[0]);
      this.searchText = selectedKeys[0];
      this.searchedColumn = dataIndex;
      // this.$forceUpdate();
    },
    handleReset(clearFilters) {
      clearFilters();
      this.searchText = '';
    },
    onRefresh() {
      this.fetch()
    },
  },
}
</script>

<style>
#operationButton {
  text-align: right;
  padding: 20px;
}
</style>
